import {defineStore} from "pinia";
import {RouteRecordRaw} from "vue-router";
import {getPermCode} from "/@/api/sys/user";
import {useMessage} from "/@/hooks/web/useMessage";
import {getMenuList} from "/@/api/sys/menu";
import {transformObjToRoute} from "/@/router/helper/routeHelper";
import {RouteItem} from "/@/api/sys/model/menuModel";
import {PAGE_NOT_FOUND_ROUTE} from "/@/router/basis";
import {store} from "/@/store";

interface PermissionState {
    // 权限代码列表
    permCodeList: string[] | number[];
    // 路由是否动态添加
    isDynamicAddedRoute: boolean;
    // 触发菜单更新
    lastBuildMenuTime: number;
    // 后台菜单列表
    backMenuList: RouteRecordRaw[];
    // 菜单列表
    frontMenuList: RouteRecordRaw[];
}

export const usePermissionStore = defineStore({
    id: 'permission',
    state: (): PermissionState => ({
        // 权限代码列表
        permCodeList: [],
        // 路由是否动态添加
        isDynamicAddedRoute: false,
        // 触发菜单更新
        lastBuildMenuTime: 0,
        // 后台菜单列表
        backMenuList: [],
        // 菜单列表
        frontMenuList: [],
    }),
    getters: {
        getPermCodeList(): string[] | number[] {
            return this.permCodeList;
        },
        getBackMenuList(): RouteRecordRaw[] {
            return this.backMenuList;
        },
        getFrontMenuList(): RouteRecordRaw[] {
            return this.frontMenuList;
        },
        getLastBuildMenuTime(): number {
            return this.lastBuildMenuTime;
        },
        getIsDynamicAddedRoute(): boolean {
            return this.isDynamicAddedRoute;
        },
    },
    actions: {
        setPermCodeList(codeList: string[]) {
            this.permCodeList = codeList;
        },

        setBackMenuList(list: RouteRecordRaw[]) {
            this.backMenuList = list;
            list?.length > 0 && this.setLastBuildMenuTime();
        },

        setFrontMenuList(list: RouteRecordRaw[]) {
            this.frontMenuList = list;
        },

        setLastBuildMenuTime() {
            this.lastBuildMenuTime = new Date().getTime();
        },

        setDynamicAddedRoute(added: boolean) {
            this.isDynamicAddedRoute = added;
        },
        resetState(): void {
            this.isDynamicAddedRoute = false;
            this.permCodeList = [];
            this.backMenuList = [];
            this.lastBuildMenuTime = 0;
        },
        async changePermissionCode() {
            const codeList = await getPermCode();
            this.setPermCodeList(codeList);
        },
        async buildRoutesAction(): Promise<RouteRecordRaw[] | null> {
            let routes: RouteRecordRaw[] = [];
            //获取后台菜单，动态生成对应路由
            const { createMessage } = useMessage();

            createMessage.loading({
                content: '加载菜单中...',
                duration: 1,
            });

            // !Simulate to obtain permission codes from the background,
            // 模拟从后台获取权限码，
            // this function may only need to be executed once, and the actual project can be put at the right time by itself
            // 这个功能可能只需要执行一次，实际项目可以自己放在合适的时间
            let routeList: RouteRecordRaw[] = [];
            try {
                await this.changePermissionCode();
                routeList = (await getMenuList() as RouteRecordRaw[]) ;
            } catch (error) {
                console.error(error);
            }

            // Dynamically introduce components
            // 动态引入组件
            routeList = transformObjToRoute(routeList as RouteItem[]);
            //  Background routing to menu structure
            //  后台路由到菜单结构
            this.setBackMenuList(routeList);

            routes = [PAGE_NOT_FOUND_ROUTE, ...routeList];
            return routes
        }
    }
})


// Need to be used outside the setup
// 需要在设置之外使用
export function usePermissionStoreWithOut() {
    return usePermissionStore(store);
}
